package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.IdWorker;
import com.example.common.R;
import com.example.domain.AddressBook;
import com.example.domain.OrderDetail;
import com.example.domain.Orders;
import com.example.domain.ShoppingCart;
import com.example.dto.OrdersDto;
import com.example.service.AddressBookService;
import com.example.service.OrderDetailService;
import com.example.service.OrderService;
import com.example.service.ShoppingCartService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")
@ResponseBody
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String beginTime,String endTime,String number)
    {
        int pageCount=(page-1)*pageSize;
        Page<Orders> p=new Page<>(page,pageSize);
        log.info("----------------------");
        log.info(beginTime);
        log.info(endTime);
        if(beginTime==null && endTime==null)
        {
            if(number==null)
            {
                List<Orders> selectpage = orderService.selectpage(pageCount, pageSize);
                log.info(selectpage.toString());
                p.setRecords(selectpage);
                int selectcount = orderService.selectcount();
                p.setTotal(selectcount);
                log.info(p.getRecords().toString());
                return R.success(p);
            }
            else
            {
                Orders selectbynumber = orderService.selectbynumber( pageCount, pageSize, number);
                List<Orders> o=new ArrayList<>();
                o.add(selectbynumber);
                p.setRecords(o);
                p.setTotal(1);
                return R.success(p);
            }
        }
        else
        {
            if(number==null)
            {
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime beginTime1 = LocalDateTime.parse(beginTime,df);
                LocalDateTime endTime1 = LocalDateTime.parse(endTime,df);

                List<Orders> selectpagebytime = orderService.selectpagebytime(pageCount, pageSize, beginTime1, endTime1);
                p.setRecords(selectpagebytime);
                int selectcount = orderService.selectcount();
                p.setTotal(selectcount);
                log.info(p.getRecords().toString());
                return R.success(p);
            }
            else
            {
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime beginTime1 = LocalDateTime.parse(beginTime,df);
                LocalDateTime endTime1 = LocalDateTime.parse(endTime,df);

                Orders selectbynumberandtime = orderService.selectbynumberandtime(pageCount, pageSize, number, beginTime1, endTime1);
                List<Orders> o=new ArrayList<>();
                o.add(selectbynumberandtime);
                p.setRecords(o);
                p.setTotal(1);
                return R.success(p);
            }
        }
    }
    @PostMapping("/submit")
    public R<Orders> submit(@RequestBody Orders orders,HttpSession session)
    {
        Long user = (Long) session.getAttribute("user");
        List<ShoppingCart> selectall = shoppingCartService.selectall(user);
        BigDecimal sum=new BigDecimal(0);
        for(int i=0;i<selectall.size();i++)
        {
            ShoppingCart shoppingCart = selectall.get(i);
            BigDecimal amount = shoppingCart.getAmount();
            sum=sum.add(amount);
        }
        IdWorker idWorker=new IdWorker();

        orders.setId(idWorker.nextId());
        orders.setNumber(String.valueOf(idWorker.nextId()));
        orders.setStatus(1);
        orders.setUserId(user);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());//支付完成的时间，要进行修改54
        orders.setAmount(sum);
        AddressBook selectbydefault = addressBookService.selectbydefault(user);
        orders.setPhone(selectbydefault.getPhone());
        orders.setAddress(selectbydefault.getDetail());
        orders.setUserName(user.toString());
        orders.setConsignee(selectbydefault.getConsignee());
        orderService.save(orders);

        for(int i=0;i<selectall.size();i++)
        {
            ShoppingCart shoppingCart = selectall.get(i);
            OrderDetail detail=new OrderDetail();
            detail.setId(idWorker.nextId());
            detail.setName(shoppingCart.getName());
            detail.setImage(shoppingCart.getImage());
            detail.setOrderId(orders.getId());
            detail.setNumber(shoppingCart.getNumber());
            detail.setAmount(shoppingCart.getAmount());
            if(shoppingCart.getDishId()!=null)
            {
                detail.setDishId(shoppingCart.getDishId());
                detail.setDishFlavor(shoppingCart.getDishFlavor());
                orderDetailService.insertdish(detail);
            }
            else
            {
                detail.setSetmealId(shoppingCart.getSetmealId());
                orderDetailService.insertsetmeal(detail);
            }
        }

        shoppingCartService.clean(user);
        return R.success(orders);
    }

    @GetMapping("/userPage")
    public R<Page> userPage(int page,int pageSize,HttpSession session)
    {
        Long user = (Long) session.getAttribute("user");
        int pageCount=(page-1)*pageSize;
        Page<Orders> p=new Page<>(page,pageSize);
            List<Orders> selectall = orderService.selectall(user, pageCount, pageSize);
            p.setRecords(selectall);
            int selectcount = orderService.selectcount1(user);
            p.setTotal(selectcount);
            Page<OrdersDto> dtoPage=new Page<>();
        BeanUtils.copyProperties(dtoPage,p,"records");
        log.info(String.valueOf(dtoPage.getTotal()));
        List<OrdersDto> ordersDtos=new ArrayList<>();
           for(int i=0;i<selectall.size();i++)
           {
               OrdersDto ordersDto=new OrdersDto();
               Orders orders = selectall.get(i);

               ordersDto.setId(orders.getId());
               ordersDto.setNumber(orders.getNumber());
               ordersDto.setStatus(orders.getStatus());
               ordersDto.setUserId(orders.getUserId());
               ordersDto.setAddressBookId(orders.getAddressBookId());
               ordersDto.setOrderTime(orders.getOrderTime());
               ordersDto.setCheckoutTime(orders.getCheckoutTime());
               ordersDto.setPayMethod(orders.getPayMethod());
               ordersDto.setAmount(orders.getAmount());
               ordersDto.setRemark(orders.getRemark());
               ordersDto.setPhone(orders.getPhone());
               ordersDto.setAddress(orders.getAddress());
               ordersDto.setUserName(orders.getUserName());
               ordersDto.setConsignee(orders.getConsignee());

               Long id = orders.getId();
               List<OrderDetail> selectbyorder = orderDetailService.selectbyorder(id);
               ordersDto.setOrderDetails(selectbyorder);
               ordersDtos.add(ordersDto);
           }
           dtoPage.setRecords(ordersDtos);
            return R.success(dtoPage);
    }


}
